package com.quectel.util.common;

import cn.hutool.core.bean.copier.BeanCopier;
import cn.hutool.core.bean.copier.CopyOptions;
import com.quectel.util.ex.common.BeanCopyException;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

public class CopyUtils {
    /**
     * 拷贝list
     *
     * @param fromList 来源
     * @param clazz    拷贝后list的泛型
     * @param <T>
     * @return
     */
    public static <T> List<T> copyList(List<?> fromList, Class<T> clazz) {

        List<T> toList = new ArrayList<>();

        if (fromList != null && fromList.size() > 0) {
            for (Object fromObj : fromList) {
                try {
                    T t = clazz.newInstance();
                    BeanUtils.copyProperties(fromObj, t);
                    toList.add(t);
                } catch (Exception e) {
                    throw new BeanCopyException("Copy bean list error");
                }

            }
        }
        return toList;
    }

    /**
     * 拷贝一个对象
     *
     * @param fromObj 来源
     * @param clazz   拷贝后list的泛型
     * @param <T>
     * @return
     */
    public static <T> T copyObj(Object fromObj, Class<T> clazz) {

        if (fromObj != null) {
            try {
                T t = clazz.newInstance();
                BeanUtils.copyProperties(fromObj, t);
                return t;
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (Exception e) {
                throw new BeanCopyException("Copy bean list error");
            }
        }

        return null;
    }

    /**
     * 拷贝一个对象到另一个对象
     *
     * @param source            来源
     * @param dest              来源
     * @param isIgnoreNullValue 遇到null是否跳过 true跳过null
     * @return
     */
    public static void copyTo(Object source, Object dest, boolean isIgnoreNullValue) {
        BeanCopier.create(source, dest, CopyOptions.create().setIgnoreNullValue(isIgnoreNullValue)).copy();

    }
}
